<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useForm, useFormRules } from '@/hooks/common/form';
import { $t } from '@/locales';
import { UserApi } from '@/api-services/apis/user-api';
import { feature, getAPI } from '@/axios-utils';
import { queryDone } from '@/utils/api';
import { REG_PWD, REG_USER_NAME } from '@/constants/reg';
import { ApiroleserviceApi } from '@/api-services/apis/apiroleservice-api';
import { NetoKit } from '@/typings/neto';
import { ApiSysEmailSendRecordInput, SysemailsendrecordApi } from '@/api-services';

defineOptions({
  name: 'EmailRecordOperateModal'
});

interface Props {
  /** the type of operation */
  operateType: UI.TableOperateType;
  /** the edit row data */
  editId?: number | undefined;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<UI.TableOperateType, string> = {
    //添加邮件发送记录
    add: $t('page.emailManage.emailSendRecord.add'),
    //编辑邮件发送记录
    edit: $t('page.emailManage.emailSendRecord.edit'),
  };
  return titles[props.operateType];
});

// const regs: Record<UI.TableOperateType, App.Global.FormRule> = {
//   edit: { required: false },
//   add: {
//     required: true,
//     pattern: REG_PWD,
//     message: $t('form.pwd.invalid'),
//     trigger: 'change'
//   }
// };

// type Model = NonNullable<Pick<
//   ApiUserOut,
//   'account' | 'nick' | 'phone' | 'email' | 'isEnable'
// >>;
type Model = NetoKit.IsNonNullable<{
  [K in keyof Pick<ApiSysEmailSendRecordInput,
    'id' | 'templateType' | 'subject' | 'senderName' | 'senderEmail' | 'receiveName' | 'receiveEmail' |
    'state' | 'pars' | 'content' | 'sendResult' | 'isVerCode' | 'verCode' | 'isUse'>]: ApiSysEmailSendRecordInput[K];
}> & { expireTime: Date | undefined; }
const model = ref(createDefaultModel());
// string转换为number
// model.value.roleIds = model.value.roleIdStr?.split(',').map(Number);
function createDefaultModel(): Model {
  return {
    id: 0,
    templateType: 0,
    subject: '',
    content: '',
    senderName: '',
    senderEmail: '',
    receiveName: '',
    receiveEmail: '',
    state: 0,
    isVerCode: false,
    verCode: '',
    isUse: false,
    pars: '',
    sendResult: '',
    expireTime: undefined
  };
}



async function handleInitModel() {
  model.value = createDefaultModel();

  if (props.operateType === 'edit' && props.editId) {
    const [err, res] = await feature(getAPI(SysemailsendrecordApi).get(props.editId));
    queryDone(err, () => {
      if (res?.data.data) {
        // if (!res.data.data.content) {
        //   res.data.data.content = '';
        // }
        Object.assign(model.value, res?.data.data);
      }
    })
  }
}

function closeModal() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  if (props.operateType === 'add') {
    const [err, res] = await feature(getAPI(SysemailsendrecordApi).insert(model.value));

    queryDone(err, async () => {
      if (res?.data.data) {
        window.$message?.success($t('common.addSuccess'));
        closeModal();
        emit('submitted');
      }
    });
  } else {
    const [err, res] = await feature(getAPI(SysemailsendrecordApi).update(model.value));

    queryDone(err, async () => {
      if (res?.data.data) {
        window.$message?.success($t('common.updateSuccess'));
        closeModal();
        emit('submitted');
      }
    });
  }

}
type RuleKey = Extract<keyof Model, 'emailSmtpHost' | 'emailSmtpPort' | 'emailAccount' | 'sendMode'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  emailSmtpHost: defaultRequiredRule,
  emailSmtpPort: defaultRequiredRule,
  emailAccount: defaultRequiredRule,
  sendMode: defaultRequiredRule
};

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
    // getRoleOptions();
  }
});
</script>

<template>
  <NModal v-model:open="visible" :title="title" width="1000px" :show-full-screen="true">
    <ElForm ref="formRef" :model="model" :rules="rules" label-width="auto">
      <ElRow :gutter="16" wrap>
        <!-- 模板类型 -->
        <ElCol :span="12">
          <ElFormItem :label="$t('page.emailManage.emailSendRecord.templateType')" name="templateType">
            <ElSelect v-model="model.templateType">
              <ElOption :value="0" :label="$t('page.emailManage.emailSendRecord.form.templateTypeEnum.placeholder')" />

              <ElOption :value="1001" :label="$t('page.emailManage.emailSendRecord.form.templateTypeEnum.register')" />
              <ElOption :value="1002" :label="$t('page.emailManage.emailSendRecord.form.templateTypeEnum.updatePwd')" />
              <ElOption :value="1003"
                :label="$t('page.emailManage.emailSendRecord.form.templateTypeEnum.updateEmail')" />
              <ElOption :value="1004" :label="$t('page.emailManage.emailSendRecord.form.templateTypeEnum.resetPwd')" />
            </ElSelect>
          </ElFormItem>
        </ElCol>

        <!-- 状态 -->
        <ElCol :span="12">
          <ElFormItem :label="$t('page.emailManage.emailSendRecord.state')" name="state">
            <ElSelect v-model="model.state">
              <ElOption :value="0" :label="$t('page.emailManage.emailSendRecord.stateEnum.notSent')" />
              <ElOption :value="1" :label="$t('page.emailManage.emailSendRecord.stateEnum.hasBeenSent')" />
              <ElOption :value="2" :label="$t('page.emailManage.emailSendRecord.stateEnum.failSent')" />
            </ElSelect>
          </ElFormItem>
        </ElCol>

        <!-- 主题 -->
        <ElCol :span="24">
          <ElFormItem :label="$t('page.emailManage.emailSendRecord.subject')" name="subject">
            <ElInput v-model="model.subject" />
          </ElFormItem>
        </ElCol>

        <!-- 内容 -->
        <ElCol :span="24">
          <ElFormItem :label="$t('page.emailManage.emailSendRecord.content')" name="content">
            <NEditor v-model="model.content"></NEditor>
          </ElFormItem>
        </ElCol>

        <!-- 发件人信息 -->
        <ElCol :span="12">
          <ElFormItem :label="$t('page.emailManage.emailSendRecord.senderName')" name="senderName">
            <ElInput v-model="model.senderName" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem :label="$t('page.emailManage.emailSendRecord.senderEmail')" name="senderEmail">
            <ElInput v-model="model.senderEmail" />
          </ElFormItem>
        </ElCol>

        <!-- 收件人信息 -->
        <ElCol :span="12">
          <ElFormItem :label="$t('page.emailManage.emailSendRecord.receiveName')" name="receiveName">
            <ElInput v-model="model.receiveName" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem :label="$t('page.emailManage.emailSendRecord.receiveEmail')" name="receiveEmail">
            <ElInput v-model="model.receiveEmail" />
          </ElFormItem>
        </ElCol>

        <!-- 开关组 -->
        <ElCol :span="12">
          <ElFormItem :label="$t('page.emailManage.emailSendRecord.isVerCode')" name="isVerCode">
            <ElSwitch v-model:model-value="model.isVerCode" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem :label="$t('page.emailManage.emailSendRecord.isUse')" name="isUse">
            <ElSwitch v-model:model-value="model.isUse" />
          </ElFormItem>
        </ElCol>

        <!-- 验证码 -->
        <ElCol v-show="model.isVerCode" :span="12">
          <ElFormItem :label="$t('page.emailManage.emailSendRecord.verCode')" name="verCode">
            <ElInput v-model="model.verCode" />
          </ElFormItem>
        </ElCol>

        <!-- 过期时间 -->
        <ElCol :span="12">
          <ElFormItem :label="$t('page.emailManage.emailSendRecord.expireTime')" name="expireTime">
            <ElDatePicker v-model="model.expireTime" type="datetime" format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
          </ElFormItem>
        </ElCol>
        <!-- 参数 -->
        <ElCol :span="24">
          <ElFormItem :label="$t('page.emailManage.emailSendRecord.pars')" name="pars">
            <ElInput type="textarea" v-model="model.pars" :auto-size="{ minRows: 3 }" />
          </ElFormItem>
        </ElCol>

        <!-- 发送结果 -->
        <ElCol :span="24">
          <ElFormItem :label="$t('page.emailManage.emailSendRecord.sendResult')" name="sendResult">
            <ElInput v-model="model.sendResult" />
          </ElFormItem>
        </ElCol>


      </ElRow>

    </ElForm>
    <template #footer>
      <ElSpace :size="16">
        <ElButton @click="closeModal">{{ $t('common.cancel') }}</ElButton>
        <ElButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</ElButton>
      </ElSpace>
    </template>
  </NModal>
</template>

<style scoped></style>
